﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using Exentials.Xoox.Styles;

namespace Exentials.Xoox.Spreadsheet
{
    public class XWorkbook : XDocumentBase<WorkbookPart>
    {
        private XSheets _xsheets;
        private XSharedStrings _xSharedStrings;
        private XStyles _styles;
        private int _ids = 1;

        public XWorkbook(WorkbookPart workbookPart)
            : base(workbookPart)
        {
            Document.Add(new XElement(SpreadsheetSchemas.MainSchema + "workbook", new XAttribute(XNamespace.Xmlns + "r", SpreadsheetSchemas.Relationships.NamespaceName)));
        }

        public XSheets Sheets
        {
            get
            {
                if (_xsheets == null)
                {
                    _xsheets = new XSheets(this);
                    base.Document.Root.Add(_xsheets.GetXElement());
                }
                return _xsheets;
            }
        }

        public XSharedStrings SharedStrings
        {
            get
            {
                if (_xSharedStrings == null) _xSharedStrings = new XSharedStrings(DocumentPart.AddNewPart<SharedStringTablePart>(GetNewId()));
                return _xSharedStrings;
            }
        }

        public XStyles Styles
        {
            get
            {
                if (_styles == null) _styles = new XStyles(DocumentPart.AddNewPart<WorkbookStylesPart>(GetNewId()));
                return _styles;
            }
        }

        internal string GetNewId()
        {
            return string.Format("rId{0}", _ids++);
        }

        internal override void Save()
        {
            base.Save();
            _xsheets.Save();
            if (_xSharedStrings != null) _xSharedStrings.Save();
            if (_styles != null) _styles.Save();
        }
    }
}
